package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: com.hmdp.utils-> Logintnerceptor
 * @description: 这是一个拦截器，用于刷新token有效期
 * @author: chenhs
 * @createDate: 2024-03-02 22:42
 * @version: 1.0
 */
public class RefreshInterceptor implements HandlerInterceptor {
    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private StringRedisTemplate stringRedisTemplate;

    /*前置拦截*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        System.out.println("请求头中的token："+token);
//        判断token是否获取成功,token为空直接放行
        if (StrUtil.isBlank(token)) {
            return true;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        if (userMap.isEmpty()) {
            return true;
        }
        //      存在保存用户信息    userMap：存值的map， new UserDTO()：需要转换为那个实体类，false表示忽略空值。
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
//        重置token过期时间
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+ token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
//        放行
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /*后置拦截器*/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        删除用户
        UserHolder.removeUser();
    }
}
